Skip to main content
ICT
Lesson A7 - Simple I/O
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

A. Reading Input with the Scanner Class page 3 of 7

  1. Some of the programs from the preceding lessons have been written without any flexibility. To change any of the data values in the programs, it is necessary to change the variable initializations, recompile the program, and run it again. Sometimes prompting the user for a value and then processing the data is more efficient and convenient.

  2. However, accepting user input in Java can be complex. Throughout this curriculum, we will use the Scanner class to make processing input easier and less tedious.

  3. Just as the System class provides System.out for output, there is an object for input, System.in. Unfortunately, Java’s System.in object does not directly support convenient methods for reading numbers and strings. We need to have a class sitting between the System.in object and ourselves to filter what comes through. This is what the Scanner class does.

  4. Scanner is part of the java.util package, so we need to start off by adding the Scanner class to our import section.

    import java.util.Scanner;

  5. Next, we create our Scanner object and pass in the System.in object.

    Scanner in = new Scanner(System.in);

    This tells the Scanner to look at the System.in object for all of its input. In Student Lesson A13, we will learn how to change the object we pass to the Scanner so that we can read the data stored in text files.

  6. Here are some example statements:

    When the statement num1 = in.nextInt() is encountered, the program pauses until an appropriate value is entered on the keyboard.

  7. Any whitespace (spaces, tabs, newline) will separate input values. When reading values, whitespace keystrokes are ignored.

  8. When requesting data from the user via the keyboard, it is good programming practice to provide a prompt. An unintroduced input statement leaves the user hanging without a clue of what the program wants. For example:

    System.out.print("Enter an integer --> ");
    number = in.nextInt();

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.